<?php

namespace sframe;

class Config
{
	private static $config = [];
	
	private static $files = [];
	
	/**
	 * 加载配置
	 * @param string $name: 配置名
	 * @return bool
	 */
	public static function load($name)
	{
		$name = trim($name, '.');
		if(!preg_match('#^[\w\-\.]*$#i', $name)){
			return false;
		}
		
		$config = false;
		$file = str_replace(strstr($name, '.'), '', $name);
		$file = $file ? trim($file) : 'config';
		
		if(!isset(static::$files[$file])){
			$fileName = CONFIG_PATH . $file . '.php';
			if(is_file($fileName)){
				static::$files[$file] = 1;
				$config = include $fileName;
			}
		}

		if(defined('PHP_ENV')){
			$fileEnv = PHP_ENV . '/' . $file;
			if(!isset(static::$files[$fileEnv])) {
				$fileEnvName = CONFIG_PATH . $fileEnv . '.php';
				if (is_file($fileEnvName)) {
					static::$files[$file] = 1;
					static::$files[$fileEnv] = 1;
					$config2 = include $fileEnvName;
					$config = $config ? (array_replace_recursive($config,$config2)) : $config2;
				}
			}
		}
		
		if($config){
			static::$config[$file] = isset(static::$config[$file]) ? array_replace_recursive(static::$config[$file], $config) : $config;
		}
		
		return $config;
	}
	
	/**
	 * 获取配置参数，支持无限层，健名区分大小写
	 * 注意：第一个 "." 左边的部分视为配置文件名，默认为 config.
	 * sframe\Config::get();
	 * sframe\Config::get("app_id");
	 * sframe\Config::get("config.app_id");
	 * sframe\Config::get("config.a.b.c");
	 *
	 * @param string $name
	 * @param null $defaultValue
	 * @return mixed|null
	 */
	public static function get($name = '', $defaultValue = null)
	{
		$name = trim($name, '.');
		$loaded = static::load($name);
		if(is_null($name) || $name === ''){
			return array_get("config", static::$config);
		}
		if($loaded === false && preg_match('#^[\w\-\.]*$#i', $name) && strstr($name, 'config') === false){
			$name = 'config.' . $name;
			static::load($name);
		}
		$config = array_get($name, static::$config);
		return !is_null($config) ? $config : $defaultValue;
	}
	
	/**
	 * 动态设置配置参数，健名区分大小写
	 * \Config::set("config.a.b.c", "abc");
	 *
	 * @param string $name 配置变量
	 * @param mixed $value 配置值
	 * @return bool
	 */
	public static function set($name = null, $value = null)
	{
	
	}
}
